﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
using System.Net;
using System.IO.Compression;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace BaccaratRally.Client
{
    public partial class FormMain : Form
    {
        public List<Bet> BetList;

        Bitmap hostPic1 = null;
        Bitmap guestPic1 = null;
        Bitmap equalPic1 = null;

        Bitmap hostPic2 = null;
        Bitmap guestPic2 = null;
        Bitmap equalPic2 = null;

        Bitmap hostPic3 = null;
        Bitmap guestPic3 = null;
        Bitmap equalPic3 = null;

        public int blockWidth = 27;
        public int blockHeight = 35;

        public Boolean TableStatus1;
        public Boolean TableStatus2;
        public Boolean TableStatus3;

        public Boolean ShowGame;
        public DateTime LastSubmitTime;

        public DateTime LastSetTime1;
        public DateTime LastSetTime2;
        public DateTime LastSetTime3;

        public Byte Online;
        public Byte OtherSideOnline;

        public FormMain()
        {
            InitializeComponent();
            this.Text += " 当前用户: [" + CurrUser.UserName + "]";
            FillSiteList();
            BetList = new List<Bet>() { };
            ShowGame = true;
            LastSubmitTime = DateTime.Now.AddMinutes(-1);
            this.txbOffset.Text = ConfigurationManager.AppSettings["ScreenOffset"];

            LastSetTime1 = DateTime.Now.AddMinutes(-1);
            LastSetTime2 = DateTime.Now.AddMinutes(-1);
            LastSetTime3 = DateTime.Now.AddMinutes(-1);

            Online = 1;
            OtherSideOnline = 1;

            this.wbMain.AllowWebBrowserDrop = false;
            ((SHDocVw.DWebBrowserEvents_Event)wbMain.ActiveXInstance).NewWindow += wbMain_NewWindow;
        }

        public void FillSiteList()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServiceUrl"] + "SiteList.aspx");

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            String resultstring = "";

            if (response.ContentEncoding == "gzip")
            {
                Stream outStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true);
                StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
                outStream.Close();
            }
            else
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
            }

            if (resultstring.Contains("$"))
            {
                string[] sl = resultstring.Split(new char[] { '|' });
                for (int i = 0; i < sl.Length; i++)
                {
                    this.cbbSiteList.Items.Add(sl[i]);
                }
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (this.cbbSiteList.SelectedItem == null)
            {
                return;
            }

            if (this.cbbSiteList.SelectedItem.ToString().Contains("$"))
            {
                this.wbMain.Navigate(this.cbbSiteList.SelectedItem.ToString().Split(new char[] { '$' })[1].Trim());
            }
            else
            {
                return;
            }

        }

        private void btnStartGame_Click(object sender, EventArgs e)
        {
            if (btnStartGame.Text == "开始")
            {
                HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                foreach (HtmlElement ele in eles)
                {
                    if (ele.InnerHtml.Contains("MultiBetEmbed.swf"))
                    {
                        ele.Parent.Parent.Id = "";
                        ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility: visible;";
                    }
                    if (ele.Id == "ele-livetop-obj")
                    {
                        ele.Parent.Parent.Id = "";
                        ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility: visible;";

                        HtmlElement elediv = wbMain.Document.Window.Frames[0].Document.GetElementById("page-container");
                        if (elediv != null)
                        {
                            elediv.Id = "";
                        }
                    }
                }

                Online = 1;
                OtherSideOnline = 1;
                Alert(Color.Black);

                CurrUser.Pos = this.cbbPos.SelectedItem.ToString();
                CurrUser.Site = this.cbbSiteList.SelectedItem.ToString().Split(new char[] { '$' })[0].Trim();
                btnStartGame.Text = "暂停";
                OnStart();
                timerMain.Enabled = true;
                timerMain.Start();
            }
            else
            {
                timerMain.Stop();
                btnStartGame.Text = "开始";
                this.TopMost = false;
            }

        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            timerMain.Stop();
            this.TopMost = true;

            #region Check Online
            CheckOnline();

            if (Online == 0 || OtherSideOnline == 0)
            {
                Alert(Color.Red);
                return;
            }
            #endregion

            #region GetTable Status
            TableStatus1 = CanSetBet(1);
            TableStatus2 = CanSetBet(2);
            TableStatus3 = CanSetBet(3);
            #endregion

            #region Set Bet & Submit
            List<Bet> betlistneedset = (from bl in BetList where bl.BetStatus < 2 orderby bl.BetID ascending select bl).ToList();
            string roundstring = "";

            if (betlistneedset.Count > 0)
            {
                foreach (Bet b in betlistneedset)
                {
                    if (roundstring.Contains(b.TableNo.ToString()))
                    {
                        continue;
                    }

                    roundstring += b.TableNo.ToString();

                    if (b.BetStatus == 0)
                    {
                        ClickBet(b.TableNo, b.Direction, b.BetSize);
                        lock (BetList)
                        {
                            (from tbl in BetList where tbl.BetID == b.BetID select tbl).FirstOrDefault().BetStatus += 1;
                        }
                    }

                    if (b.BetStatus == 1 && LastSubmitTime.AddSeconds(4) < DateTime.Now)
                    {
                        ClickSubmit(b.TableNo);
                        SetBetStatus(b.BetID, 2);

                        lock (BetList)
                        {
                            (from tbl in BetList where tbl.BetID == b.BetID select tbl).FirstOrDefault().BetStatus += 1;
                        }
                    }


                }
            }
            #endregion

            #region Get & Set Game Result

            if (!TableStatus1)
            {
                Byte gameResult1 = GetLastGameResult1();
                if (gameResult1 > 0)
                {
                    SetGameResult(1, gameResult1);
                }
            }

            if (!TableStatus2)
            {
                Byte gameResult2 = GetLastGameResult2();
                if (gameResult2 > 0)
                {
                    SetGameResult(2, gameResult2);
                }
            }

            if (!TableStatus3)
            {
                Byte gameResult3 = GetLastGameResult3();
                if (gameResult3 > 0)
                {
                    SetGameResult(3, gameResult3);
                }
            }
            #endregion

            KeepAlive(TableStatus1, TableStatus2, TableStatus3);

            Calc();

            timerMain.Start();
        }

        private void OnStart()
        {
            LastSetTime1 = DateTime.Now.AddMinutes(-1);
            LastSetTime2 = DateTime.Now.AddMinutes(-1);
            LastSetTime3 = DateTime.Now.AddMinutes(-1);
            LastSubmitTime = DateTime.Now.AddMinutes(-1);

            BetList.Clear();

            this.lbTableSizeTotal.Text = "0";
            this.lbTableWinTotal.Text = "0";

            this.lbTableSize1.Text = "0";
            this.lbTableWin1.Text = "0";

            this.lbTableSize2.Text = "0";
            this.lbTableWin2.Text = "0";

            this.lbTableSize3.Text = "0";
            this.lbTableWin3.Text = "0";


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServiceUrl"] + "OnStart.aspx?AccountName=" + CurrUser.UserName + "&AccountPos=" + this.cbbPos.SelectedItem.ToString());

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            String resultstring = "";

            if (response.ContentEncoding == "gzip")
            {
                Stream outStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true);
                StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
                outStream.Close();
            }
            else
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
            }
        }

        #region Keep Alive
        private void KeepAlive(bool tablestatus1, bool tablestatus2, bool tablestatus3)
        {
            String url = ConfigurationManager.AppSettings["ServiceUrl"] + "KeepAlive.aspx?AccountName=" + CurrUser.UserName + "&AccountPos=" + this.cbbPos.SelectedItem.ToString() + "&Site=" + CurrUser.Site;
            url += "&Ts=" + (tablestatus1 ? "1" : "0") + "|" + (tablestatus2 ? "1" : "0") + "|" + (tablestatus3 ? "1" : "0");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            request.BeginGetResponse(new AsyncCallback(server_KeepAliveCompleted), request);
        }

        void server_KeepAliveCompleted(IAsyncResult ar)
        {
            String result = "";
            try
            {
                #region Get HttpRequest Result
                HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

                if (response.ContentEncoding == "gzip")
                {
                    Stream outStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true);
                    StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("UTF-8"));
                    result = reader.ReadToEnd();
                    reader.Close();
                    outStream.Close();
                }
                else
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                    result = reader.ReadToEnd();
                    reader.Close();
                }

                #endregion

            }
            catch
            {
                return;
            }
            if (result.Contains("-"))
            {
                string[] bs = result.Split(new char[] { '|' });
                for (int i = 0; i < bs.Length; i++)
                {
                    string[] bis = bs[i].Split(new char[] { '-' });

                    int c = (from bl in BetList where bl.BetID == int.Parse(bis[0]) select bl).Count();
                    if (c == 0)
                    {
                        if (bis[3] == "1" && LastSetTime1 < DateTime.Now.AddSeconds(-20))
                        {
                            LastSetTime1 = DateTime.Now;
                            lock (BetList)
                            {
                                BetList.Add(new Bet() { BetID = int.Parse(bis[0]), AccountName = CurrUser.UserName, AccountPos = CurrUser.Pos, BetSize = Decimal.Parse(bis[2]), Direction = bis[1], BetStatus = 0, TableNo = Byte.Parse(bis[3]) });
                            }
                        }

                        if (bis[3] == "2" && LastSetTime2 < DateTime.Now.AddSeconds(-20))
                        {
                            LastSetTime2 = DateTime.Now;
                            lock (BetList)
                            {
                                BetList.Add(new Bet() { BetID = int.Parse(bis[0]), AccountName = CurrUser.UserName, AccountPos = CurrUser.Pos, BetSize = Decimal.Parse(bis[2]), Direction = bis[1], BetStatus = 0, TableNo = Byte.Parse(bis[3]) });
                            }
                        }

                        if (bis[3] == "3" && LastSetTime3 < DateTime.Now.AddSeconds(-20))
                        {
                            LastSetTime3 = DateTime.Now;
                            lock (BetList)
                            {
                                BetList.Add(new Bet() { BetID = int.Parse(bis[0]), AccountName = CurrUser.UserName, AccountPos = CurrUser.Pos, BetSize = Decimal.Parse(bis[2]), Direction = bis[1], BetStatus = 0, TableNo = Byte.Parse(bis[3]) });
                            }
                        }

                    }
                }
            }
        }

        private void CheckOnline()
        {
            Byte isonline = IsOnline();

            Online = isonline;

            String url = ConfigurationManager.AppSettings["ServiceUrl"] + "Online.aspx?AccountName=" + CurrUser.UserName + "&AccountPos=" + this.cbbPos.SelectedItem.ToString() + "&Online=" + isonline.ToString();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            request.BeginGetResponse(new AsyncCallback(server_CheckOnlineCompleted), request);
        }

        void server_CheckOnlineCompleted(IAsyncResult ar)
        {
            String result = "";
            try
            {
                #region Get HttpRequest Result
                HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

                if (response.ContentEncoding == "gzip")
                {
                    Stream outStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true);
                    StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("UTF-8"));
                    result = reader.ReadToEnd();
                    reader.Close();
                    outStream.Close();
                }
                else
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                    result = reader.ReadToEnd();
                    reader.Close();
                }

                #endregion

            }
            catch
            {
                return;
            }

            OtherSideOnline = Byte.Parse(result);
        }
        #endregion

        #region SetBet Status
        private void SetBetStatus(int betID, Byte betStatus)
        {
            String url = ConfigurationManager.AppSettings["ServiceUrl"] + "SetBet.aspx?BetID=" + betID.ToString() + "&BetStatus=" + betStatus.ToString();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            request.BeginGetResponse(new AsyncCallback(server_SetBetStatusCompleted), request);
        }

        private void SetBetStatus(int betID, Byte betStatus, String betResult, Decimal betProfit)
        {
            String url = ConfigurationManager.AppSettings["ServiceUrl"] + "SetBet.aspx?BetID=" + betID.ToString() + "&BetStatus=" + betStatus.ToString() + "&BetProfit=" + betProfit.ToString() + "&BetResult=" + betResult;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            request.BeginGetResponse(new AsyncCallback(server_SetBetStatusCompleted), request);
        }

        void server_SetBetStatusCompleted(IAsyncResult ar)
        {

        }
        #endregion

        private bool CanSetBet(int tableno)
        {
            bool result;
            int x = 180;
            int y = 449;

            x = x + int.Parse(this.txbOffset.Text) + (tableno - 1) * 286;


            Bitmap i;
            Graphics g;

            i = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            g = Graphics.FromImage(i);
            g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));

            if (i.GetPixel(x, y).R == i.GetPixel(x, y).G && i.GetPixel(x, y).B == i.GetPixel(x, y).G)
            {
                result = false;
            }
            else if (int.Parse(i.GetPixel(x, y).R.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) < 300)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            if (tableno == 1) lbStatus1.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();
            if (tableno == 2) lbStatus2.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();
            if (tableno == 3) lbStatus3.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();


            g.Dispose();
            i.Dispose();

            return result;
        }

        private void Calc()
        {
            this.lbTableSizeTotal.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" select bl.BetSize).Sum().ToString();
            this.lbTableWinTotal.Text = (from bl in BetList where bl.BetStatus == 6 select bl.BetProfit).Sum().ToString();

            this.lbTableSize1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 1 select bl.BetSize).Sum().ToString();
            this.lbTableWin1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 select bl.BetProfit).Sum().ToString();

            this.lbTableSize2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 2 select bl.BetSize).Sum().ToString();
            this.lbTableWin2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 select bl.BetProfit).Sum().ToString();

            this.lbTableSize3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 3 select bl.BetSize).Sum().ToString();
            this.lbTableWin3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 select bl.BetProfit).Sum().ToString();
        }

        #region Get Game Result
        public Byte GetLastGameResult1()
        {
            Byte result = 0;

            try
            {
                int locationX = 16 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic1 == null || guestPic1 == null || equalPic1 == null)
                {
                    hostPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic1);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic1);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic1);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic1);
                    float guest = ImageComparison(current_guestPic, guestPic1);
                    float equal = ImageComparison(current_equalPic, equalPic1);

                    if (host < 1)
                    {
                        hostPic1 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic1 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic1 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 0;
                        hostPic1 = current_hostPic;
                        guestPic1 = current_guestPic;
                        equalPic1 = current_equalPic;
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte GetLastGameResult2()
        {
            Byte result = 0;

            try
            {
                int locationX = 302 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic2 == null || guestPic2 == null || equalPic2 == null)
                {
                    hostPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic2);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic2);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic2);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic2);
                    float guest = ImageComparison(current_guestPic, guestPic2);
                    float equal = ImageComparison(current_equalPic, equalPic2);

                    if (host < 1)
                    {
                        hostPic2 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic2 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic2 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 0;
                        hostPic2 = current_hostPic;
                        guestPic2 = current_guestPic;
                        equalPic2 = current_equalPic;
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte GetLastGameResult3()
        {
            Byte result = 0;

            try
            {
                int locationX = 587 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic3 == null || guestPic3 == null || equalPic3 == null)
                {
                    hostPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic3);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic3);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic3);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic3);
                    float guest = ImageComparison(current_guestPic, guestPic3);
                    float equal = ImageComparison(current_equalPic, equalPic3);

                    if (host < 1)
                    {
                        hostPic3 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic3 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic3 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 0;
                        hostPic3 = current_hostPic;
                        guestPic3 = current_guestPic;
                        equalPic3 = current_equalPic;
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte IsOnline()
        {
            Byte result;
            int x = 568;
            int y = 330;

            Bitmap i;
            Graphics g;

            i = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            g = Graphics.FromImage(i);
            g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));

            if (int.Parse(i.GetPixel(x, y).R.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) < 100)
            {
                result = 0;
            }
            else
            {
                result = 1;
            }

            g.Dispose();
            i.Dispose();

            return result;

        }
        #endregion

        #region Set Game Result
        private void SetGameResult(Byte tableno, Byte gameResult)
        {
            var betItem = (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault();

            String betResult;
            Decimal betProfit = 0M;

            if (betItem != null)
            {
                if (gameResult == 9 && betItem.Direction == "B")
                {
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetResult = "W";
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetProfit = betItem.BetSize * 0.95M;

                    betResult = "W";
                    betProfit = betItem.BetSize * 0.95M;
                }
                else if (gameResult == 1 && betItem.Direction == "V")
                {
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetResult = "W";
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetProfit = betItem.BetSize;

                    betResult = "W";
                    betProfit = betItem.BetSize;
                }
                else if (gameResult == 5)
                {
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetResult = "D";
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetProfit = 0M;

                    betResult = "D";
                }
                else
                {
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetResult = "L";
                    (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetProfit = 0M - betItem.BetSize;

                    betResult = "L";
                    betProfit = 0 - betItem.BetSize;
                }

                (from bi in BetList where bi.BetStatus == 2 && bi.TableNo == tableno select bi).FirstOrDefault().BetStatus = 6;

                SetBetStatus(betItem.BetID, 6, betResult, betProfit);

            }
        }
        #endregion

        #region ClickBet & Submit
        private void ClickBet(Byte tableno, string direction, Decimal betsize)
        {
            string bsize = betsize.ToString("F0");
            if (bsize.Length > 3)
            {
                int tcount = int.Parse(bsize[bsize.Length - 4].ToString());
                ClickChip(tcount, 4, direction, tableno);
            }

            if (bsize.Length > 2)
            {
                int tcount = int.Parse(bsize[bsize.Length - 3].ToString());
                ClickChip(tcount, 3, direction, tableno);
            }

            if (bsize.Length > 1)
            {
                int tcount = int.Parse(bsize[bsize.Length - 2].ToString());
                ClickChip(tcount, 2, direction, tableno);
            }
        }

        private void ClickChip(int count, int psize, string direction, Byte tableno)
        {
            if (count == 0) return;

            //计算筹码坐标
            int ybase = 495;
            int xbase = 80 + int.Parse(this.txbOffset.Text) + (tableno - 1) * 285 + (psize - 2) * 44;
            //计算庄闲位置坐标
            int ydbase = 400;
            int xdbase = ((direction == "B") ? 230 : 88) + (tableno - 1) * 285;

            //点击筹码
            SetCursorPos(xbase + this.Location.X, ybase + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);

            Thread.Sleep(500);


            //点击庄闲位置
            for (int i = 0; i < count; i++)
            {
                SetCursorPos(xdbase + this.Location.X, ydbase + this.Location.Y);
                mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
            }

        }

        private void ClickSubmit(Byte tableno)
        {
            int ybase = 450;
            int xbase = 216 + (tableno - 1) * 285;

            SetCursorPos(xbase + this.Location.X, ybase + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);

            LastSubmitTime = DateTime.Now;
        }
        #endregion

        #region Base Func for Click & Window
        public float ImageComparison(Bitmap img1, Bitmap img2)
        {
            if (img1.Width == img2.Width && img1.Height == img2.Height && img1.Width != 0 && img1.Height != 0)
            {
                int equalCount = 0;

                for (int i = 0; i < img1.Width; i++)
                {
                    for (int j = 0; j < img1.Height; j++)
                    {
                        if (img1.GetPixel(i, j) == img2.GetPixel(i, j))
                        {
                            equalCount++;
                        }
                    }
                }

                return (float)equalCount / (img1.Width * img1.Height);
            }
            else
            {
                return 0;
            }
        }

        public void wbMain_NewWindow(string url, int flag, string target, ref object data, string header, ref bool processed)
        {
            processed = true;
            wbMain.Navigate(url);
        }

        /// <summary>
        /// 这部分是控制鼠标定位的基础类和方法，不用管，已经封装好了。
        /// </summary>
        #region Mouse Base Action
        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);
        [Flags]
        enum MouseEventFlag : uint
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000
        }

        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int cButtons, int dwExtraInfo);
        #endregion

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData.ToString() == "F3")
            {
                this.lbPos.Text = MousePosition.X.ToString() + "," + MousePosition.Y.ToString() + "    |  " + this.Location.X.ToString() + "," + this.Location.Y.ToString();
            }

            if (keyData.ToString() == "F4")
            {
                Bitmap i;
                Graphics g;

                i = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                g = Graphics.FromImage(i);
                g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));

                this.lbPos.Text = i.GetPixel(MousePosition.X - Location.X, MousePosition.Y - Location.Y).R.ToString() + "," + i.GetPixel(MousePosition.X - Location.X, MousePosition.Y - Location.Y).G.ToString() + "," + i.GetPixel(MousePosition.X - Location.X, MousePosition.Y - Location.Y).B.ToString();

                g.Dispose();
                i.Dispose();
            }

            if (keyData.ToString() == "F2")
            {
                if (btnStartGame.Text == "开始")
                {
                    HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                    foreach (HtmlElement ele in eles)
                    {
                        if (ele.InnerHtml.Contains("MultiBetEmbed.swf")) ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility: visible;";
                    }

                    CurrUser.Pos = this.cbbPos.SelectedItem.ToString();
                    CurrUser.Site = this.cbbSiteList.SelectedItem.ToString().Split(new char[] { '$' })[0].Trim();
                    btnStartGame.Text = "暂停";
                    OnStart();
                    

                    timerMain.Enabled = true;
                    timerMain.Start();
                }
                else
                {
                    timerMain.Stop();
                    btnStartGame.Text = "开始";
                    this.TopMost = false;
                }
            }

            if (keyData.ToString() == "F9")
            {
                OpenResultForm();
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        private void btnShowGame_Click(object sender, EventArgs e)
        {
            if (ShowGame)
            {
                HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                foreach (HtmlElement ele in eles)
                {
                    if (ele.InnerHtml.Contains("MultiBetEmbed.swf")) ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility:hidden;";
                    if (ele.Id == "ele-livetop-obj")
                    {
                        ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility:hidden;";
                    }
                }

                ShowGame = false;
            }
            else
            {
                HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                foreach (HtmlElement ele in eles)
                {
                    if (ele.InnerHtml.Contains("MultiBetEmbed.swf")) ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility:visible;";
                    if (ele.Id == "ele-livetop-obj")
                    {
                        ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility:visible;;";
                    }
                }

                ShowGame = true;
            }
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            FormSetting formSetting = new FormSetting();
            formSetting.Show();
        }

        private void OpenResultForm()
        {
            HtmlElementCollection eles = wbMain.Document.GetElementById("MMainData").All;

            List<string> urllist = new List<string>() { };

            foreach (HtmlElement ele in eles)
            {
                if (ele.TagName == "A")
                {
                    if (ele.GetAttribute("href").Contains("GameResult.php")) urllist.Add(ele.GetAttribute("href"));
                }
            }

            FormResult formResult = new FormResult(urllist);
            formResult.Show();
        }

        private void Alert(Color c)
        {
            this.lbStatus1.ForeColor = c;
            this.lbStatus2.ForeColor = c;
            this.lbStatus3.ForeColor = c;

            this.lbTableSize1.ForeColor = c;
            this.lbTableSize2.ForeColor = c;
            this.lbTableSize3.ForeColor = c;

            this.lbTableSizeTotal.ForeColor = c;

            this.lbTableWin1.ForeColor = c;
            this.lbTableWin2.ForeColor = c;
            this.lbTableWin3.ForeColor = c;

            this.lbTableWinTotal.ForeColor = c;
        }

        private void btnFindResult_Click(object sender, EventArgs e)
        {
            OpenResultForm();
        }
    }
}
